home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.5 / threading.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2007-05-11  |  22.9 KB  |  835 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. """Thread module emulating a subset of Java's threading model."""
  5. import sys as _sys
  6.  
  7. try:
  8.     import thread
  9. except ImportError:
  10.     del _sys.modules[__name__]
  11.     raise 
  12.  
  13. from time import time as _time, sleep as _sleep
  14. from traceback import format_exc as _format_exc
  15. from collections import deque
  16. __all__ = [
  17.     'activeCount',
  18.     'Condition',
  19.     'currentThread',
  20.     'enumerate',
  21.     'Event',
  22.     'Lock',
  23.     'RLock',
  24.     'Semaphore',
  25.     'BoundedSemaphore',
  26.     'Thread',
  27.     'Timer',
  28.     'setprofile',
  29.     'settrace',
  30.     'local',
  31.     'stack_size']
  32. _start_new_thread = thread.start_new_thread
  33. _allocate_lock = thread.allocate_lock
  34. _get_ident = thread.get_ident
  35. ThreadError = thread.error
  36. del thread
  37. _VERBOSE = False
  38.  
  39. class _Verbose(object):
  40.     
  41.     def __init__(self, verbose = None):
  42.         if verbose is None:
  43.             verbose = _VERBOSE
  44.         
  45.         self._Verbose__verbose = verbose
  46.  
  47.     
  48.     def _note(self, format, *args):
  49.         if self._Verbose__verbose:
  50.             format = format % args
  51.             format = '%s: %s\n' % (currentThread().getName(), format)
  52.             _sys.stderr.write(format)
  53.         
  54.  
  55.  
  56. _profile_hook = None
  57. _trace_hook = None
  58.  
  59. def setprofile(func):
  60.     global _profile_hook
  61.     _profile_hook = func
  62.  
  63.  
  64. def settrace(func):
  65.     global _trace_hook
  66.     _trace_hook = func
  67.  
  68. Lock = _allocate_lock
  69.  
  70. def RLock(*args, **kwargs):
  71.     return _RLock(*args, **kwargs)
  72.  
  73.  
  74. class _RLock(_Verbose):
  75.     
  76.     def __init__(self, verbose = None):
  77.         _Verbose.__init__(self, verbose)
  78.         self._RLock__block = _allocate_lock()
  79.         self._RLock__owner = None
  80.         self._RLock__count = 0
  81.  
  82.     
  83.     def __repr__(self):
  84.         if self._RLock__owner:
  85.             pass
  86.         return '<%s(%s, %d)>' % (self.__class__.__name__, self._RLock__owner.getName(), self._RLock__count)
  87.  
  88.     
  89.     def acquire(self, blocking = 1):
  90.         me = currentThread()
  91.         if self._RLock__owner is me:
  92.             self._RLock__count = self._RLock__count + 1
  93.             self._note('%s.acquire(%s): recursive success', self, blocking)
  94.             return 1
  95.         
  96.         rc = self._RLock__block.acquire(blocking)
  97.         if rc:
  98.             self._RLock__owner = me
  99.             self._RLock__count = 1
  100.             self._note('%s.acquire(%s): initial success', self, blocking)
  101.         else:
  102.             self._note('%s.acquire(%s): failure', self, blocking)
  103.         return rc
  104.  
  105.     __enter__ = acquire
  106.     
  107.     def release(self):
  108.         me = currentThread()
  109.         if not self._RLock__owner is me:
  110.             raise AssertionError, 'release() of un-acquire()d lock'
  111.         self._RLock__count = count = self._RLock__count - 1
  112.         if not count:
  113.             self._RLock__owner = None
  114.             self._RLock__block.release()
  115.             self._note('%s.release(): final release', self)
  116.         else:
  117.             self._note('%s.release(): non-final release', self)
  118.  
  119.     
  120.     def __exit__(self, t, v, tb):
  121.         self.release()
  122.  
  123.     
  124.     def _acquire_restore(self, .1):
  125.         (count, owner) = .1
  126.         self._RLock__block.acquire()
  127.         self._RLock__count = count
  128.         self._RLock__owner = owner
  129.         self._note('%s._acquire_restore()', self)
  130.  
  131.     
  132.     def _release_save(self):
  133.         self._note('%s._release_save()', self)
  134.         count = self._RLock__count
  135.         self._RLock__count = 0
  136.         owner = self._RLock__owner
  137.         self._RLock__owner = None
  138.         self._RLock__block.release()
  139.         return (count, owner)
  140.  
  141.     
  142.     def _is_owned(self):
  143.         return self._RLock__owner is currentThread()
  144.  
  145.  
  146.  
  147. def Condition(*args, **kwargs):
  148.     return _Condition(*args, **kwargs)
  149.  
  150.  
  151. class _Condition(_Verbose):
  152.     
  153.     def __init__(self, lock = None, verbose = None):
  154.         _Verbose.__init__(self, verbose)
  155.         if lock is None:
  156.             lock = RLock()
  157.         
  158.         self._Condition__lock = lock
  159.         self.acquire = lock.acquire
  160.         self.release = lock.release
  161.         
  162.         try:
  163.             self._release_save = lock._release_save
  164.         except AttributeError:
  165.             pass
  166.  
  167.         
  168.         try:
  169.             self._acquire_restore = lock._acquire_restore
  170.         except AttributeError:
  171.             pass
  172.  
  173.         
  174.         try:
  175.             self._is_owned = lock._is_owned
  176.         except AttributeError:
  177.             pass
  178.  
  179.         self._Condition__waiters = []
  180.  
  181.     
  182.     def __enter__(self):
  183.         return self._Condition__lock.__enter__()
  184.  
  185.     
  186.     def __exit__(self, *args):
  187.         return self._Condition__lock.__exit__(*args)
  188.  
  189.     
  190.     def __repr__(self):
  191.         return '<Condition(%s, %d)>' % (self._Condition__lock, len(self._Condition__waiters))
  192.  
  193.     
  194.     def _release_save(self):
  195.         self._Condition__lock.release()
  196.  
  197.     
  198.     def _acquire_restore(self, x):
  199.         self._Condition__lock.acquire()
  200.  
  201.     
  202.     def _is_owned(self):
  203.         if self._Condition__lock.acquire(0):
  204.             self._Condition__lock.release()
  205.             return False
  206.         else:
  207.             return True
  208.  
  209.     
  210.     def wait(self, timeout = None):
  211.         if not self._is_owned():
  212.             raise AssertionError, 'wait() of un-acquire()d lock'
  213.         waiter = _allocate_lock()
  214.         waiter.acquire()
  215.         self._Condition__waiters.append(waiter)
  216.         saved_state = self._release_save()
  217.         
  218.         try:
  219.             if timeout is None:
  220.                 waiter.acquire()
  221.                 self._note('%s.wait(): got it', self)
  222.             else:
  223.                 endtime = _time() + timeout
  224.                 delay = 0.0005
  225.                 while True:
  226.                     gotit = waiter.acquire(0)
  227.                     if gotit:
  228.                         break
  229.                     
  230.                     remaining = endtime - _time()
  231.                     if remaining <= 0:
  232.                         break
  233.                     
  234.                     delay = min(delay * 2, remaining, 0.05)
  235.                     _sleep(delay)
  236.                 if not gotit:
  237.                     self._note('%s.wait(%s): timed out', self, timeout)
  238.                     
  239.                     try:
  240.                         self._Condition__waiters.remove(waiter)
  241.                     except ValueError:
  242.                         pass
  243.                     except:
  244.                         None<EXCEPTION MATCH>ValueError
  245.                     
  246.  
  247.                 None<EXCEPTION MATCH>ValueError
  248.                 self._note('%s.wait(%s): got it', self, timeout)
  249.         finally:
  250.             self._acquire_restore(saved_state)
  251.  
  252.  
  253.     
  254.     def notify(self, n = 1):
  255.         if not self._is_owned():
  256.             raise AssertionError, 'notify() of un-acquire()d lock'
  257.         _Condition__waiters = self._Condition__waiters
  258.         waiters = _Condition__waiters[:n]
  259.         if not waiters:
  260.             self._note('%s.notify(): no waiters', self)
  261.             return None
  262.         
  263.         if not n != 1 or 's':
  264.             pass
  265.         self._note('%s.notify(): notifying %d waiter%s', self, n, '')
  266.         for waiter in waiters:
  267.             waiter.release()
  268.             
  269.             try:
  270.                 _Condition__waiters.remove(waiter)
  271.             continue
  272.             except ValueError:
  273.                 continue
  274.             
  275.  
  276.         
  277.  
  278.     
  279.     def notifyAll(self):
  280.         self.notify(len(self._Condition__waiters))
  281.  
  282.  
  283.  
  284. def Semaphore(*args, **kwargs):
  285.     return _Semaphore(*args, **kwargs)
  286.  
  287.  
  288. class _Semaphore(_Verbose):
  289.     
  290.     def __init__(self, value = 1, verbose = None):
  291.         if not value >= 0:
  292.             raise AssertionError, 'Semaphore initial value must be >= 0'
  293.         _Verbose.__init__(self, verbose)
  294.         self._Semaphore__cond = Condition(Lock())
  295.         self._Semaphore__value = value
  296.  
  297.     
  298.     def acquire(self, blocking = 1):
  299.         rc = False
  300.         self._Semaphore__cond.acquire()
  301.         while self._Semaphore__value == 0:
  302.             if not blocking:
  303.                 break
  304.             
  305.             self._note('%s.acquire(%s): blocked waiting, value=%s', self, blocking, self._Semaphore__value)
  306.             self._Semaphore__cond.wait()
  307.         self._Semaphore__value = self._Semaphore__value - 1
  308.         self._note('%s.acquire: success, value=%s', self, self._Semaphore__value)
  309.         rc = True
  310.         self._Semaphore__cond.release()
  311.         return rc
  312.  
  313.     __enter__ = acquire
  314.     
  315.     def release(self):
  316.         self._Semaphore__cond.acquire()
  317.         self._Semaphore__value = self._Semaphore__value + 1
  318.         self._note('%s.release: success, value=%s', self, self._Semaphore__value)
  319.         self._Semaphore__cond.notify()
  320.         self._Semaphore__cond.release()
  321.  
  322.     
  323.     def __exit__(self, t, v, tb):
  324.         self.release()
  325.  
  326.  
  327.  
  328. def BoundedSemaphore(*args, **kwargs):
  329.     return _BoundedSemaphore(*args, **kwargs)
  330.  
  331.  
  332. class _BoundedSemaphore(_Semaphore):
  333.     '''Semaphore that checks that # releases is <= # acquires'''
  334.     
  335.     def __init__(self, value = 1, verbose = None):
  336.         _Semaphore.__init__(self, value, verbose)
  337.         self._initial_value = value
  338.  
  339.     
  340.     def release(self):
  341.         if self._Semaphore__value >= self._initial_value:
  342.             raise ValueError, 'Semaphore released too many times'
  343.         
  344.         return _Semaphore.release(self)
  345.  
  346.  
  347.  
  348. def Event(*args, **kwargs):
  349.     return _Event(*args, **kwargs)
  350.  
  351.  
  352. class _Event(_Verbose):
  353.     
  354.     def __init__(self, verbose = None):
  355.         _Verbose.__init__(self, verbose)
  356.         self._Event__cond = Condition(Lock())
  357.         self._Event__flag = False
  358.  
  359.     
  360.     def isSet(self):
  361.         return self._Event__flag
  362.  
  363.     
  364.     def set(self):
  365.         self._Event__cond.acquire()
  366.         
  367.         try:
  368.             self._Event__flag = True
  369.             self._Event__cond.notifyAll()
  370.         finally:
  371.             self._Event__cond.release()
  372.  
  373.  
  374.     
  375.     def clear(self):
  376.         self._Event__cond.acquire()
  377.         
  378.         try:
  379.             self._Event__flag = False
  380.         finally:
  381.             self._Event__cond.release()
  382.  
  383.  
  384.     
  385.     def wait(self, timeout = None):
  386.         self._Event__cond.acquire()
  387.         
  388.         try:
  389.             if not self._Event__flag:
  390.                 self._Event__cond.wait(timeout)
  391.         finally:
  392.             self._Event__cond.release()
  393.  
  394.  
  395.  
  396. _counter = 0
  397.  
  398. def _newname(template = 'Thread-%d'):
  399.     global _counter
  400.     _counter = _counter + 1
  401.     return template % _counter
  402.  
  403. _active_limbo_lock = _allocate_lock()
  404. _active = { }
  405. _limbo = { }
  406.  
  407. class Thread(_Verbose):
  408.     __initialized = False
  409.     __exc_info = _sys.exc_info
  410.     
  411.     def __init__(self, group = None, target = None, name = None, args = (), kwargs = None, verbose = None):
  412.         if not group is None:
  413.             raise AssertionError, 'group argument must be None for now'
  414.         _Verbose.__init__(self, verbose)
  415.         if kwargs is None:
  416.             kwargs = { }
  417.         
  418.         self._Thread__target = target
  419.         if not name:
  420.             pass
  421.         self._Thread__name = str(_newname())
  422.         self._Thread__args = args
  423.         self._Thread__kwargs = kwargs
  424.         self._Thread__daemonic = self._set_daemon()
  425.         self._Thread__started = False
  426.         self._Thread__stopped = False
  427.         self._Thread__block = Condition(Lock())
  428.         self._Thread__initialized = True
  429.         self._Thread__stderr = _sys.stderr
  430.  
  431.     
  432.     def _set_daemon(self):
  433.         return currentThread().isDaemon()
  434.  
  435.     
  436.     def __repr__(self):
  437.         if not self._Thread__initialized:
  438.             raise AssertionError, 'Thread.__init__() was not called'
  439.         status = 'initial'
  440.         if self._Thread__started:
  441.             status = 'started'
  442.         
  443.         if self._Thread__stopped:
  444.             status = 'stopped'
  445.         
  446.         if self._Thread__daemonic:
  447.             status = status + ' daemon'
  448.         
  449.         return '<%s(%s, %s)>' % (self.__class__.__name__, self._Thread__name, status)
  450.  
  451.     
  452.     def start(self):
  453.         if not self._Thread__initialized:
  454.             raise AssertionError, 'Thread.__init__() not called'
  455.         if not not (self._Thread__started):
  456.             raise AssertionError, 'thread already started'
  457.         self._note('%s.start(): starting thread', self)
  458.         _active_limbo_lock.acquire()
  459.         _limbo[self] = self
  460.         _active_limbo_lock.release()
  461.         _start_new_thread(self._Thread__bootstrap, ())
  462.         self._Thread__started = True
  463.         _sleep(1e-06)
  464.  
  465.     
  466.     def run(self):
  467.         if self._Thread__target:
  468.             self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
  469.         
  470.  
  471.     
  472.     def __bootstrap(self):
  473.         
  474.         try:
  475.             self._Thread__started = True
  476.             _active_limbo_lock.acquire()
  477.             _active[_get_ident()] = self
  478.             del _limbo[self]
  479.             _active_limbo_lock.release()
  480.             self._note('%s.__bootstrap(): thread started', self)
  481.             if _trace_hook:
  482.                 self._note('%s.__bootstrap(): registering trace hook', self)
  483.                 _sys.settrace(_trace_hook)
  484.             
  485.             if _profile_hook:
  486.                 self._note('%s.__bootstrap(): registering profile hook', self)
  487.                 _sys.setprofile(_profile_hook)
  488.             
  489.             
  490.             try:
  491.                 self.run()
  492.             except SystemExit:
  493.                 self._note('%s.__bootstrap(): raised SystemExit', self)
  494.             except:
  495.                 self._note('%s.__bootstrap(): unhandled exception', self)
  496.                 if _sys:
  497.                     _sys.stderr.write('Exception in thread %s:\n%s\n' % (self.getName(), _format_exc()))
  498.                 else:
  499.                     (exc_type, exc_value, exc_tb) = self._Thread__exc_info()
  500.                     
  501.                     try:
  502.                         print >>self._Thread__stderr, 'Exception in thread ' + self.getName() + ' (most likely raised during interpreter shutdown):'
  503.                         print >>self._Thread__stderr, 'Traceback (most recent call last):'
  504.                         while exc_tb:
  505.                             print >>self._Thread__stderr, '  File "%s", line %s, in %s' % (exc_tb.tb_frame.f_code.co_filename, exc_tb.tb_lineno, exc_tb.tb_frame.f_code.co_name)
  506.                             exc_tb = exc_tb.tb_next
  507.                         print >>self._Thread__stderr, '%s: %s' % (exc_type, exc_value)
  508.                     finally:
  509.                         del exc_type
  510.                         del exc_value
  511.                         del exc_tb
  512.  
  513.  
  514.             self._note('%s.__bootstrap(): normal return', self)
  515.         finally:
  516.             self._Thread__stop()
  517.             
  518.             try:
  519.                 self._Thread__delete()
  520.             except:
  521.                 pass
  522.  
  523.  
  524.  
  525.     
  526.     def __stop(self):
  527.         self._Thread__block.acquire()
  528.         self._Thread__stopped = True
  529.         self._Thread__block.notifyAll()
  530.         self._Thread__block.release()
  531.  
  532.     
  533.     def __delete(self):
  534.         '''Remove current thread from the dict of currently running threads.'''
  535.         _active_limbo_lock.acquire()
  536.         
  537.         try:
  538.             del _active[_get_ident()]
  539.         except KeyError:
  540.             if 'dummy_threading' not in _sys.modules:
  541.                 raise 
  542.             
  543.         except:
  544.             'dummy_threading' not in _sys.modules
  545.         finally:
  546.             _active_limbo_lock.release()
  547.  
  548.  
  549.     
  550.     def join(self, timeout = None):
  551.         if not self._Thread__initialized:
  552.             raise AssertionError, 'Thread.__init__() not called'
  553.         if not self._Thread__started:
  554.             raise AssertionError, 'cannot join thread before it is started'
  555.         if not self is not currentThread():
  556.             raise AssertionError, 'cannot join current thread'
  557.         if not self._Thread__stopped:
  558.             self._note('%s.join(): waiting until thread stops', self)
  559.         
  560.         self._Thread__block.acquire()
  561.         
  562.         try:
  563.             if timeout is None:
  564.                 while not self._Thread__stopped:
  565.                     self._Thread__block.wait()
  566.                 self._note('%s.join(): thread stopped', self)
  567.             else:
  568.                 deadline = _time() + timeout
  569.                 while not self._Thread__stopped:
  570.                     delay = deadline - _time()
  571.                     if delay <= 0:
  572.                         self._note('%s.join(): timed out', self)
  573.                         break
  574.                     
  575.                     self._Thread__block.wait(delay)
  576.                 self._note('%s.join(): thread stopped', self)
  577.         finally:
  578.             self._Thread__block.release()
  579.  
  580.  
  581.     
  582.     def getName(self):
  583.         if not self._Thread__initialized:
  584.             raise AssertionError, 'Thread.__init__() not called'
  585.         return self._Thread__name
  586.  
  587.     
  588.     def setName(self, name):
  589.         if not self._Thread__initialized:
  590.             raise AssertionError, 'Thread.__init__() not called'
  591.         self._Thread__name = str(name)
  592.  
  593.     
  594.     def isAlive(self):
  595.         if not self._Thread__initialized:
  596.             raise AssertionError, 'Thread.__init__() not called'
  597.         if self._Thread__started:
  598.             pass
  599.         return not (self._Thread__stopped)
  600.  
  601.     
  602.     def isDaemon(self):
  603.         if not self._Thread__initialized:
  604.             raise AssertionError, 'Thread.__init__() not called'
  605.         return self._Thread__daemonic
  606.  
  607.     
  608.     def setDaemon(self, daemonic):
  609.         if not self._Thread__initialized:
  610.             raise AssertionError, 'Thread.__init__() not called'
  611.         if not not (self._Thread__started):
  612.             raise AssertionError, 'cannot set daemon status of active thread'
  613.         self._Thread__daemonic = daemonic
  614.  
  615.  
  616.  
  617. def Timer(*args, **kwargs):
  618.     return _Timer(*args, **kwargs)
  619.  
  620.  
  621. class _Timer(Thread):
  622.     """Call a function after a specified number of seconds:
  623.  
  624.     t = Timer(30.0, f, args=[], kwargs={})
  625.     t.start()
  626.     t.cancel() # stop the timer's action if it's still waiting
  627.     """
  628.     
  629.     def __init__(self, interval, function, args = [], kwargs = { }):
  630.         Thread.__init__(self)
  631.         self.interval = interval
  632.         self.function = function
  633.         self.args = args
  634.         self.kwargs = kwargs
  635.         self.finished = Event()
  636.  
  637.     
  638.     def cancel(self):
  639.         """Stop the timer if it hasn't finished yet"""
  640.         self.finished.set()
  641.  
  642.     
  643.     def run(self):
  644.         self.finished.wait(self.interval)
  645.         if not self.finished.isSet():
  646.             self.function(*self.args, **self.kwargs)
  647.         
  648.         self.finished.set()
  649.  
  650.  
  651.  
  652. class _MainThread(Thread):
  653.     
  654.     def __init__(self):
  655.         Thread.__init__(self, name = 'MainThread')
  656.         self._Thread__started = True
  657.         _active_limbo_lock.acquire()
  658.         _active[_get_ident()] = self
  659.         _active_limbo_lock.release()
  660.  
  661.     
  662.     def _set_daemon(self):
  663.         return False
  664.  
  665.     
  666.     def _exitfunc(self):
  667.         self._Thread__stop()
  668.         t = _pickSomeNonDaemonThread()
  669.         if t:
  670.             self._note('%s: waiting for other threads', self)
  671.         
  672.         while t:
  673.             t.join()
  674.             t = _pickSomeNonDaemonThread()
  675.         self._note('%s: exiting', self)
  676.         self._Thread__delete()
  677.  
  678.  
  679.  
  680. def _pickSomeNonDaemonThread():
  681.     for t in enumerate():
  682.         if not t.isDaemon() and t.isAlive():
  683.             return t
  684.             continue
  685.     
  686.  
  687.  
  688. class _DummyThread(Thread):
  689.     
  690.     def __init__(self):
  691.         Thread.__init__(self, name = _newname('Dummy-%d'))
  692.         del self._Thread__block
  693.         self._Thread__started = True
  694.         _active_limbo_lock.acquire()
  695.         _active[_get_ident()] = self
  696.         _active_limbo_lock.release()
  697.  
  698.     
  699.     def _set_daemon(self):
  700.         return True
  701.  
  702.     
  703.     def join(self, timeout = None):
  704.         if not False:
  705.             raise AssertionError, 'cannot join a dummy thread'
  706.  
  707.  
  708.  
  709. def currentThread():
  710.     
  711.     try:
  712.         return _active[_get_ident()]
  713.     except KeyError:
  714.         return _DummyThread()
  715.  
  716.  
  717.  
  718. def activeCount():
  719.     _active_limbo_lock.acquire()
  720.     count = len(_active) + len(_limbo)
  721.     _active_limbo_lock.release()
  722.     return count
  723.  
  724.  
  725. def enumerate():
  726.     _active_limbo_lock.acquire()
  727.     active = _active.values() + _limbo.values()
  728.     _active_limbo_lock.release()
  729.     return active
  730.  
  731. from thread import stack_size
  732. _shutdown = _MainThread()._exitfunc
  733.  
  734. try:
  735.     from thread import _local as local
  736. except ImportError:
  737.     from _threading_local import local
  738.  
  739.  
  740. def _test():
  741.     
  742.     class BoundedQueue(_Verbose):
  743.         
  744.         def __init__(self, limit):
  745.             _Verbose.__init__(self)
  746.             self.mon = RLock()
  747.             self.rc = Condition(self.mon)
  748.             self.wc = Condition(self.mon)
  749.             self.limit = limit
  750.             self.queue = deque()
  751.  
  752.         
  753.         def put(self, item):
  754.             self.mon.acquire()
  755.             while len(self.queue) >= self.limit:
  756.                 self._note('put(%s): queue full', item)
  757.                 self.wc.wait()
  758.             self.queue.append(item)
  759.             self._note('put(%s): appended, length now %d', item, len(self.queue))
  760.             self.rc.notify()
  761.             self.mon.release()
  762.  
  763.         
  764.         def get(self):
  765.             self.mon.acquire()
  766.             while not self.queue:
  767.                 self._note('get(): queue empty')
  768.                 self.rc.wait()
  769.             item = self.queue.popleft()
  770.             self._note('get(): got %s, %d left', item, len(self.queue))
  771.             self.wc.notify()
  772.             self.mon.release()
  773.             return item
  774.  
  775.  
  776.     
  777.     class ProducerThread(Thread):
  778.         
  779.         def __init__(self, queue, quota):
  780.             Thread.__init__(self, name = 'Producer')
  781.             self.queue = queue
  782.             self.quota = quota
  783.  
  784.         
  785.         def run(self):
  786.             random = random
  787.             import random
  788.             counter = 0
  789.             while counter < self.quota:
  790.                 counter = counter + 1
  791.                 self.queue.put('%s.%d' % (self.getName(), counter))
  792.                 _sleep(random() * 1e-05)
  793.  
  794.  
  795.     
  796.     class ConsumerThread(Thread):
  797.         
  798.         def __init__(self, queue, count):
  799.             Thread.__init__(self, name = 'Consumer')
  800.             self.queue = queue
  801.             self.count = count
  802.  
  803.         
  804.         def run(self):
  805.             while self.count > 0:
  806.                 item = self.queue.get()
  807.                 print item
  808.                 self.count = self.count - 1
  809.  
  810.  
  811.     NP = 3
  812.     QL = 4
  813.     NI = 5
  814.     Q = BoundedQueue(QL)
  815.     P = []
  816.     for i in range(NP):
  817.         t = ProducerThread(Q, NI)
  818.         t.setName('Producer-%d' % (i + 1))
  819.         P.append(t)
  820.     
  821.     C = ConsumerThread(Q, NI * NP)
  822.     for t in P:
  823.         t.start()
  824.         _sleep(1e-06)
  825.     
  826.     C.start()
  827.     for t in P:
  828.         t.join()
  829.     
  830.     C.join()
  831.  
  832. if __name__ == '__main__':
  833.     _test()
  834.  
  835.